import javabean.Userbean;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/upload")
@MultipartConfig(location = "D:\\Java EE\\experience\\experience3\\src\\main\\webapp\\image")
public class UploadFile extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        Part part = request.getPart("images");
        String filename = part.getSubmittedFileName();
        Userbean user = new Userbean();
        HttpSession session = request.getSession(true);
        if(session.getAttribute("users")!=null)
            user = (Userbean) session.getAttribute("users");
        if(!user.imageexist())
            user.saveimage();
        Date d = new Date();
        SimpleDateFormat dt = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String now = dt.format(d);
        String types[] = filename.split("[.]");
        String type = types[types.length-1];
        user.setImage(user.getUsername()+now+"."+type);
        part.write(user.getImage());
        user.changeimage();
        response.sendRedirect("http://localhost:8080/message.jsp");
    }
}
